# _*_ encoding: utf-8 _*_

import traci
import traci.constants as tc
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
import logging


class Transmission:
    def __init__(self, host, port, net_xml):
        traci.init(host=host, port=port)
        self.tlLogics = []
        self.net_xml = net_xml

    def load_tlLogic(self, net_xml):
        tree = ET.ElementTree(file=net_xml)
        for child in tree.getroot():
            if child.tag == 'tlLogic':
                attrib = [child.attrib['id']]
                for son in child:
                    attrib.append(son.attrib['state'])
                self.tlLogics.append(attrib)

    def subscribe(self):
        for tlLogic in self.tlLogics:
            traci.trafficlights.subscribe(tlsID=tlLogic[0])

    def start(self):
        self.load_tlLogic(self.net_xml)
        self.subscribe()
        self.simulate()

    def retrieve_tlLogic(self, step):
        for tlLogic in self.tlLogics:
            values = traci.trafficlights.getSubscriptionResults(tlLogic[0])
            phrase = values[tc.TL_CURRENT_PHASE]
            logging.info("{0},{1},{2},{3}".format(step, tlLogic[0], phrase, tlLogic[phrase + 1]))

    def simulate(self):
        for i in range(21600, 36001):
            print "%d" % (i)
            self.retrieve_tlLogic(i)
            traci.simulationStep()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format="%(message)s", filename="../data/1109/logs.txt", filemode="w")
    transmission = Transmission(host="localhost", port=9999, net_xml="../data/1109/hangzhou_main_road.net.xml")
    transmission.start()

